package stackAndQueue;


import java.util.LinkedList;
import java.util.Queue;

/*
* 用队列实现栈
* */
public class MyStack {
    private Queue<Integer> queue1;
    private Queue<Integer> queue2;
    public MyStack() {
        queue1 = new LinkedList<>();
        queue2 = new LinkedList<>();
    }

    //每次均向不为空的队列中增加和删除元素
    public void push(int x) {
        if(!queue1.isEmpty()){
            queue1.offer(x);
        } else if (!queue2.isEmpty()) {
            queue2.offer(x);
        } else {
            queue1.offer(x);
        }
    }

    public int pop() {
        if(empty()){
            return -1;
        }
        if(!queue1.isEmpty()) {
            int size1 = queue1.size();
            for(int i = 0; i < size1 - 1; i++){
                queue2.offer(queue1.poll());
            }
            return queue1.poll();
        } else {
            int size2 = queue2.size();
            for(int i = 0; i < size2 - 1; i++){
                queue1.offer(queue2.poll());
            }
            return queue2.poll();
        }
    }

    public int top() {
        if(empty()){
            return -1;
        }
        int tmp = -1;
        if(!queue1.isEmpty()) {
            int size1 = queue1.size();
            for(int i = 0; i < size1; i++){
                tmp = queue1.poll();
                queue2.offer(tmp);
            }
            return tmp;
        } else {
            int size2 = queue2.size();
            for(int i = 0; i < size2; i++){
                tmp = queue2.poll();
                queue1.offer(tmp);
            }
            return tmp;
        }
    }

    public boolean empty() {
        return queue1.isEmpty() && queue2.isEmpty();
    }
}
